package name.fowler.refactoring.simplestore.persistence;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;

import name.fowler.refactoring.simplestore.domain.pricecode.PriceCode;

public class PriceCodeRepository {
	@PersistenceUnit
	private EntityManagerFactory entityManagerFactory;
	
	public PriceCodeRepository() {};
	
	// This constructor is for testing only
	public PriceCodeRepository(EntityManagerFactory entityManagerFactory) {
		this.entityManagerFactory = entityManagerFactory;
	}
	
	public void addPriceCode(PriceCode pc) {
		EntityManager entityManager = entityManagerFactory.createEntityManager();
		entityManager.getTransaction().begin();
        entityManager.persist(pc);
        entityManager.getTransaction().commit();
	}
	
	public void removePriceCode(PriceCode pc) {
		EntityManager entityManager = entityManagerFactory.createEntityManager();
		entityManager.getTransaction().begin();
        entityManager.remove(pc);
        entityManager.getTransaction().commit();
	}
	
	public void updatePriceCode(PriceCode pc) {
		EntityManager entityManager = entityManagerFactory.createEntityManager();
		entityManager.getTransaction().begin();
        entityManager.merge(pc);
        entityManager.getTransaction().commit();
	}
	
	public List<PriceCode> queryAll() {
		EntityManager entityManager = entityManagerFactory.createEntityManager();
		List<PriceCode> PriceCodes = entityManager
				.createNamedQuery("PriceCode.findAll", PriceCode.class)
				.getResultList();
		entityManager.close();
		return PriceCodes;
	}
}
